package fr.umlv.ig.MetroView;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;


import javax.swing.JComponent;

import fr.umlv.ig.model.Train;

@SuppressWarnings("serial")
public class JTrain extends JComponent {

	private Train train;
	private final BufferedImage image;
	private final MouseAdapter mouseAdapter;
	
	public JTrain(final Train train) {
		this.train = train;
		this.image = new BufferedImage(10, 10, BufferedImage.TYPE_3BYTE_BGR);
		setBounds(train.getCoordinate().x, train.getCoordinate().y, 10, 10);

		mouseAdapter = new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				System.out.println("name : " + train.getName());
				System.out.println("train position : " + train.getCoordinate());
			}
		};
		addMouseListener(mouseAdapter);
	}

	public Point getPoint() {
		return train.getCoordinate();
	}
	
	@Override
	public void setBounds(int x, int y, int width, int height) {
		super.setBounds(x, y, width, height);
		train.setCoordinate(new Point(x,y));
	}
	
	@Override
	public void setLocation(int x, int y) {
		super.setLocation(x, y);
		train.setCoordinate(new Point(x,y));
	}
	
	public void move() {
		int y = train.getNextStation().getY() - train.getCurrentStation().getY();
		int x = train.getNextStation().getX() - train.getCurrentStation().getX();
		double a = y/x;
		double b = train.getCurrentStation().getY() - (a * train.getCurrentStation().getX());
		
		//for(int i=train.getCurrentStation().getX(); i<train.getNextStation().getX(); i++) {
			int i=train.getCurrentStation().getX()+5;
			setBounds(i, (int) (a*i+b), 10, 10);
			//train.setCoordinate(new Point(i,(int) (a*i+b)));
		//}
	}
	
	@Override
	public void paintComponent(Graphics g) {
		g.drawImage(image, 0, 0, 10, 10, null);
	}
	
	public void drawTrain() {
		Graphics2D gs = image.createGraphics();
		gs.setColor(Color.RED);
		gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		gs.drawOval(train.getCoordinate().x, train.getCoordinate().y, 10, 10);
		repaint();
	}
}
